package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.*;
import com.bwie.poi.ExcelUtil;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.*;
import com.bwie.service.TbOrderService;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.ProdInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 叶雨洁
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-07-23 17:15:05
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{


    @Autowired
    TbOrderMapper orderMapper;

    @Autowired
    HttpServletResponse response;

    @Autowired
    TbOrderDetailMapper detailMapper;
    @Autowired
    TbProdImageMapper prodImageMapper;

    @Autowired
    TbProdInfoMapper prodInfoMapper;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    TbOrderRecordMapper orderRecordMapper;

    @Autowired
    TbOrderDetailMapper orderDetailMapper;

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {

        Page<TbOrder> orderPage = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());
        QueryWrapper<TbOrder> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
            queryWrapper.lambda().like(TbOrder::getProdInfo,pageInfoVo.getKeyWord());
        }
        if(pageInfoVo.getOrderStatus()!=null){
            queryWrapper.lambda().eq(TbOrder::getOrderStatus,pageInfoVo.getOrderStatus());
        }
        if(pageInfoVo.getOrderType()!=null){
            queryWrapper.lambda().eq(TbOrder::getOrderType,pageInfoVo.getOrderType());
        }
        if(pageInfoVo.getOrderId()!=null){
            queryWrapper.lambda().eq(TbOrder::getOrderId,pageInfoVo.getOrderId());
        }
        orderPage.getRecords().forEach(tbOrder -> {
            List<TbOrderDetail> tbDetails = detailMapper.selectList(
                    new QueryWrapper<TbOrderDetail>().lambda().eq(TbOrderDetail::getOrderId, tbOrder.getOrderId())

                    //使用stream流 将图片转换为列表
            );

            tbDetails.forEach(detail->{
                List<TbProdImage> tbProdImages = prodImageMapper.selectList(
                        new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, detail.getProdId())
                );
                List<String> imageList = tbProdImages.stream().map(item -> item.getUrl()).collect(Collectors.toList());
                //设置图片列表
                detail.setProdImageList(imageList);

                tbOrder.setImageList(imageList);
            });

            tbOrder.setTbOrderDetails(tbDetails);
        });
        Page<TbOrder> orderPage1 = orderMapper.selectPage(orderPage, queryWrapper);
        return R.OK(orderPage1);
    }

    @Override
    public R deleteOrder(List<TbOrder> orderList) {



        for (TbOrder tbOrder : orderList) {
            orderMapper.deleteById(tbOrder);
        }
        return R.OK();
    }

    @Override
    public void export(String ids) {

        if (ids == null || ids.trim().isEmpty()) {
            // 这里可根据实际场景选择处理方式，比如抛自定义异常让上层捕获提示用户，或直接日志记录
            System.out.println("传入的 ids 为空，无法导出");
            // 如果是 Web 场景，也可通过 response 给前端返回提示：
            // response.getWriter().write("请传入有效的 ids 参数");
            return;
        }

        String[] idsplit = ids.split(",");

        ArrayList<Integer> integers = new ArrayList<>();
        for (String s : idsplit) {
            integers.add(Integer.parseInt(s));
        }

        //根据ids 查询列表
        List<TbOrder> tbOrders = orderMapper.selectBatchIds(integers);
        //开始导出文件
        ExcelUtil<TbOrder> orderExcelUtil = new ExcelUtil<TbOrder>(TbOrder.class);

        orderExcelUtil.exportExcel(response,tbOrders,"订单列表");
    }

    @Override
    public R addOrder(List<TbProdInfo> prodInfoList) {


        //1.检查商品库存，并扣除
        BigDecimal totalAmout = new BigDecimal("0");
        StringBuilder prodNames = new StringBuilder();

        //获取分布式锁
        RLock lock = redissonClient.getLock("order-lock");

        //加锁
        try {
            lock.lock();
            for (TbProdInfo prodInfo : prodInfoList) {
                TbProdInfo tbProdInfo = prodInfoMapper.selectById(prodInfo.getInfoId());
                if(prodInfo.getBuyNum() > tbProdInfo.getProdStock()) {
                    return R.ERROR(50,"库存不足");
                }

                //扣减并更新库存
                tbProdInfo.setProdStock(tbProdInfo.getProdStock() - prodInfo.getBuyNum());
                prodInfoMapper.updateById(tbProdInfo);

                //计算订单金额
                totalAmout = totalAmout.add(prodInfo.getProdPrice().multiply(new BigDecimal(prodInfo.getBuyNum())));
                //拼接商品名称
                if(prodNames.length() > 0) {
                    prodNames.append(",");
                    prodNames.append(prodInfo.getProdName());
                }else {
                    prodNames.append(prodInfo.getProdName());
                }
            }
        } finally {
            //解锁
            lock.unlock();
        }


        //2.创建订单
        TbOrder order = new TbOrder();
        //雪花算法生成订单编号
        long id = IdUtil.getSnowflake(1, 1).nextId();
        order.setOrderNo(""+id);
        order.setOrderType(1);
        order.setOrderStatus(0);
        order.setCreateTime(new Date());
//        order.setUserId(userId);
        order.setOrderAmount(totalAmout);
        order.setProdInfo(prodNames.toString());
        orderMapper.insert(order);


        //3.创建订单明细
        for (TbProdInfo prodInfo : prodInfoList) {
            TbOrderDetail orderDetail = new TbOrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setBuyNum(prodInfo.getBuyNum());
            orderDetail.setProdId(prodInfo.getProdId());
            orderDetail.setBuyPrice(prodInfo.getProdPrice());
            orderDetail.setInfoId(prodInfo.getInfoId());
            orderDetailMapper.insert(orderDetail);
        }


        //4.新增订单记录
        TbOrderRecord orderRecord = new TbOrderRecord();
        orderRecord.setOrderId(order.getOrderId());
        orderRecord.setOptRecord("用户创建订单");
        orderRecordMapper.insert(orderRecord);

        return R.OK();
    }

    @Override
    public R selectPageInfo(ProdInfoVo prodInfoVo) {

        Page<TbProdInfo> prodInfoPage = new Page<>(prodInfoVo.getPageNum(), prodInfoVo.getPageSize());
        QueryWrapper<TbProdInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(TbProdInfo::getProdId,prodInfoVo.getProdId());
        Page<TbProdInfo> tbProdInfoPage = prodInfoMapper.selectPage(prodInfoPage, queryWrapper);

        return R.OK(tbProdInfoPage);
    }
}




